package com.gitee.huxing.framework.core;

import com.alibaba.fastjson.parser.ParserConfig;
import com.gitee.huxing.framework.core.aspecj.UserMethodInterceptor;
import com.gitee.huxing.framework.core.filter.Filter;
import com.gitee.huxing.framework.core.loadbalance.LoadBalancer;
import com.gitee.huxing.framework.core.router.Router;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: RPC服务框架
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.framework.core
 * @ClassName: ServiceRpcFrx
 * @Author: huxing
 * @DateTime: 2021-09-30 上午11:25
 */
@SuppressWarnings("all")
public class ServiceRpcFrx {

    static {
        ParserConfig.getGlobalInstance().addAccept("com.gitee.huxing");
    }

    /**
     * @Description:  通过注册中心创建服务
     * @Author: huxing
     * @param serverClass
     * @param zkUrl
     * @param router
     * @param loadBalance
     * @param filter
     * @return T
     * @Date: 2021/9/30 上午11:29
     **/
    public static <T, filters> T createFromRegistry(final Class<T> serverClass, final String zkUrl, Router router, LoadBalancer loadBalance, Filter filter){
        List<String> invokers = new ArrayList<>();
        // 1. 获取服务url列表
        List<String> urls = router.route(invokers);
        // 2. 负载均衡处理请求跳转
        String url = loadBalance.select(urls);
        // 3. 创建服务处理
        return (T) create(serverClass, url, filter);
    }

    /**
     * @Description: 创建一个代理服务
     * @Author: huxing
     * @param serviceClass
     * @param url
     * @param filters
     * @return T
     * @Date: 2021/9/30 上午11:33
     **/
    public static <T> T create(final Class<T> serviceClass, final String url, Filter... filters){
        return (T) Proxy.newProxyInstance(ServiceRpcFrx.class.getClassLoader(), new Class[]{serviceClass},
                new ServiceInvocationHandler(serviceClass, url, filters));
    }

    /**
     * @Description: 创建一个代理服务
     * @Author: huxing
     * @param serviceClass
     * @param url
     * @param filters
     * @return T
     * @Date: 2021/9/30 上午11:33
     **/
    public static <T> T createTest(Class<T> serviceClass, String url, Filter... filters){
        Object proxyInterface = ServiceRpcFrx.create(serviceClass, url, filters);
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(proxyInterface);
        proxyFactory.addAdvice(new UserMethodInterceptor());
        return (T) proxyFactory.getProxy();
    }
}
